import { modal } from 'vue-strap'
import DatePicker from 'vue-datepicker'
import extend from 'extend'
import getDatePickerOption from '../../../util/date-picker-option'
import { updateIndexAd, showMsg, toogleIndexAdListFresh } from '../../../vuex/action'

const validation = {
  ad(data) {
    for (let name in data) {
      if (name === 'type' && data[name] < 0) {
        return false
      }
      if (name !== 'channel' && name !== 'file' && (data[name] + '').length === 0) {
        return false
      }
    }
    return true
  },
  time(start, end) {
    return start < end
  }
}

export default {
  name: 'IndexAdUpdate',
  props: ['ad'],
  components: {
    'vue-modal': modal,
    'vue-date-picker': DatePicker
  },
  data() {
    return {
      showUpdateAdModal: false,
      datePickerOption: getDatePickerOption()
    }
  },
  vuex: {
    actions: {
      xUpdateIndexAd: updateIndexAd,
      xShowMsg: showMsg,
      xToogleIndexAdListFresh: toogleIndexAdListFresh
    }
  },
  watch: {
    showUpdateAdModal(newVal) {
      if (!newVal) {
        this.xToogleIndexAdListFresh(1)
      }
    }
  },
  methods: {
    trim(val) {
      if (typeof val === 'string') {
        return val.replace(/(^ +)|( +$)/g, '')
      } else {
        return val
      }
    },
    updateAd() {
      this.showUpdateAdModal = true
    },
    submit() {
      var formData = new FormData()
      var ad = extend(true, {}, this.ad)

      var valid = validation.ad(ad)
      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '* 标记的均为必填/必选项'
        })
      }
      var timeValid = validation.time(ad.startTime, ad.endTime)
      if (!timeValid) {
        return this.xShowMsg({
          type: 'danger',
          content: '开始时间应早于结束时间'
        })
      }

      ad.type = +ad.type
      ad.forceExternalBrowser = +ad.forceExternalBrowser
      for (let name in ad) {
        let value = ad[name] !== null ? ad[name] : ''
        if (name !== 'file') {
          formData.append(name, this.trim(value))
        }
      }
      formData.append('file', this.$els.file.files[0])
      this.xUpdateIndexAd(formData)
        .then(() => {
          this.showUpdateAdModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
